package com.wxtbk.service;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;



import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jfinal.log.Log;
import com.wxtbk.model.WtItem;
import com.wxtbk.model.WtItemAlimama;
import com.wxtbk.model.WtItemHdk;
import com.wxtbk.scheduler.task.HaodankuTask;



public class ItemService {
	
	private  Log logger = Log.getLog(ItemService.class);
	
	public static String[] AlimamaColumns = new String[] { "item_id", "title", "url_img", "url_detail", "cat_top",
			"url_taobaoke", "price", "sales_month", "rate_income", "commission", "seller_ww", "seller_id", "shop_name",
			"shop_type", "coupon_id", "coupon_total", "coupon_left", "coupon_notes", "coupon_start", "coupon_end",
			"coupon_url", "coupon_campaign_url" };
	
	
	public void SaveHaodankuItem(String input) throws ParseException{
		
		logger.info(input);
				
		//List<WtItemHdk> lst = JSON.parseArray(input, WtItemHdk.class);
		//for (Object o : lst) 
		// (o instanceof WtItemHdk) == false   线程池中调用该方法会提示类型不符，搁置问题，采用Gson处理=> gsonzhuxianc主线程、线程池线程都返回空。
		
		/* 太麻烦，不合理
		JSONArray jsonArray = JSON.parseArray(input);
		for(int i=0;i<jsonArray.size();i++){
			jsonArray.getJSONObject(i).get("id");
			jsonArray.getJSONObject(i).get("item_id");
		}
		*/
		
		/* 主线程、线程池线程都返回空。
		Gson gson = new Gson();
		List<WtItemHdk> lst = gson.fromJson(input, new TypeToken<List<WtItemHdk>>(){}.getType());
		*/
		
		WtItemHdk.dao.DelExpiredAll();
		WtItem.dao.DelExpiredAll();
		
		List<WtItemHdk> lst = JSON.parseArray(input, WtItemHdk.class);
    	 for(Object o : lst){

    		WtItemHdk p = (WtItemHdk)o;
//    		WtItemHdk p =(WtItemHdk)o;
    		//WtItemHdk p = JSON.parseObject(o.toString(), WtItemHdk.class);
            //System.out.println(p.toString()); 
    			
    		int id = Integer.parseInt(p.getId());
    		
    		if ( WtItemHdk.dao.findByIdLoadColumns(p.getId(), "id") != null )
    		
            	WtItemHdk.dao.deleteById(p.getId());
            	p.save();
            	
    			
    			int sales = Integer.parseInt(p.getItemsale());
    			int total = Integer.parseInt(p.getCouponnum());
    			int receive = Integer.parseInt(p.getCouponreceive());
    			int left = total - receive;
    			float commission = 0;
    			float price = Float.parseFloat(p.getItemprice());
    			int catid = Integer.parseInt(p.getFqcat());
    			int beginIndex = p.getCouponurl().lastIndexOf('=')+1;
    			String couponid = p.getCouponurl().substring(beginIndex);
    			float couponmoney = Float.parseFloat(p.getCouponmoney());
    			
    			    		
    			
    			Timestamp tsStart = new Timestamp(Long.parseLong(p.getCouponstarttime())*1000);
    			Timestamp tsEnd = new Timestamp(Long.parseLong(p.getCouponendtime())*1000);
    			
    			//formater.format(tsStart);
    			    			    			
    			WtItem item = new WtItem();
    			item.setId(id);
    			item.setItemid(p.getItemid());
    			item.setItemtitle(p.getItemtitle());
    			item.setItempicurl(p.getItempic());
    			item.setItemsale(sales);
    			item.setItemprice(price);
    			item.setCouponId(couponid);
    			item.setCouponTotal(total);
    			item.setCouponLeft(left);
    			item.setCouponmoney(couponmoney);
    			item.setCouponstarttime(tsStart);
    			item.setCouponendtime(tsEnd);
    			item.setCommission(commission);
    			item.setCatid(catid);
    			
    			item.save();

    			/*
    			WtItem.dao.SaveWtItem(p.getItemid(), p.getItemtitle(), p.getItempic(), 
    					sales, price,
    					null, p.getCouponurl(), null, 
    					total, left, commission,catid,couponmoney);
    			*/    					            
    	}
	}
	public static void SaveAlimamaItem(String[][] result) {

		Pattern pattern = Pattern.compile("(\\d+)");

		int rowLength = result.length;
		for (int i = 0; i < rowLength; i++) {
			WtItemAlimama p = new WtItemAlimama();
			boolean isExists = false;
			for (int j = 0; j < result[i].length; j++) {
				Object value = result[i][j];
				
				if (j == 0) {
					//WtItemAlimama.dao.deleteById(value);
					WtItemAlimama wtali= WtItemAlimama.dao.findById(value);
					if ( wtali != null ){
						isExists = true;
						break;
					}
				} else if (j >= AlimamaColumns.length) {
					break;
				}
				String colname = AlimamaColumns[j];

				if (colname == "coupon_notes") {
					Matcher matcher = pattern.matcher((String)value);
					while (matcher.find()) {
						value = matcher.group(1);
					}
				}
				if (colname == "price" || colname == "coupon_notes") {
					//value = Float.parseFloat((String)value);

				}
				p.set(colname, value);
			}
			if (isExists) continue;
			p.save();
			//save to wt_item table.
			int sales = Integer.parseInt(p.getSalesMonth());
			int total = Integer.parseInt(p.getCouponTotal());
			int left = Integer.parseInt(p.getCouponLeft());
			float commission = Float.parseFloat(p.getCommission());
			float price =Float.parseFloat(p.getPrice());
			float couponmoney = Float.parseFloat(p.getCouponNotes());
			WtItem.dao.SaveWtItem(p.getItemId(), p.getTitle(), p.getUrlImg(), 
					sales, price,
					p.getCouponId(), p.getCouponUrl(), p.getCouponCampaignUrl(), 
					total, left, commission,14,couponmoney);

		}
		

	}

	public static void main(String[] args) throws Exception {
		
		File f = new File("f:\\hdk.json");
		InputStreamReader read = new InputStreamReader(new FileInputStream(f),"UTF-8");//考虑到编码格式
		BufferedReader bufferedReader = new BufferedReader(read);
        String lineTxt = null;
        
       
        //Thread t = new Thread(task);
        //t.start();
        
        while((lineTxt = bufferedReader.readLine()) != null){
            System.out.println(lineTxt);            
            new ItemService().SaveHaodankuItem(lineTxt);
            
        }
        read.close();
		
	}
}
